package com.tensai.core.mvc.base.service.imp;

import com.tensai.core.mvc.base.dao.IIdDao;
import com.tensai.core.mvc.base.entry.IdEntity;
import com.tensai.core.mvc.base.service.IIdService;
import com.tensai.core.mvc.base.tools.ResultJson;
import com.tensai.core.constant.ResponseStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 以ID为主键的实体类Service的基本实现类，以ID为主键的Service类必须继承此类
 *
 * @author Tensai
 * 2018-03-09 15:46
 */
@Service
public abstract class BaseIdServiceImpl<T extends IdEntity, K extends IIdDao<T>> extends BaseServiceImpl<T, Integer, K> implements IIdService<T, K> {

    /**
     * 批量删除数据
     *
     * @param qids id集合（以逗号分隔）
     * @return 删除结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultJson deletes(String qids) {
        ResultJson resultJson;
        String[] ids = qids.split(",");
        List<Integer> idList = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            try {
                Integer item = Integer.valueOf(ids[i]);
                idList.add(item);
            } catch (Exception e) {
                e.printStackTrace();
                resultJson = new ResultJson(ResponseStatus.ERROR_PARAMS);
                resultJson.addData("error", e.toString());
            }
        }
        getDao().deleteByIdIn(idList);
        resultJson = new ResultJson(ResponseStatus.DELETES_SUCCESS);
        return resultJson;
    }

    /**
     * 保存当前实体
     *
     * @param t 实体对象
     * @return 保存结果
     */
    @Override
    public ResultJson save(T t) {
        if (t != null) {
            if (t.getId() != null) {
                T t1 = getDao().findOne(t.getId());
                t = combineSydwCore(t1, t);
            }
            getDao().save(t);
            return new ResultJson(ResponseStatus.SAVE_SUCCESS);
        }
        ResultJson resultJson;
        resultJson = new ResultJson(ResponseStatus.SAVE_FAILURE);
        resultJson.addData("error", "请检查保存的数据是否为空");
        return resultJson;
    }

}
